package com.hst.capacity.domain.service.impl;

import cn.hutool.core.util.StrUtil;
import com.hst.capacity.domain.model.request.UploadParam;
import com.hst.capacity.domain.service.UploadService;
import com.hst.capacity.infra.external.qiniu.KodoService;
import com.hst.capacity.infra.util.StringUtil;
import com.qiniu.storage.model.DefaultPutRet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private KodoService kodoService;

    @Override
    public void save(MultipartFile[] multipartFile, UploadParam param) {
//        HashMap<String, String> returns = new HashMap<>();
        if (multipartFile==null)
            return;

        String[] files = param.uploadFile();
        for (String k: files){
            for (MultipartFile v:multipartFile){
                if (!StrUtil.equals(k,v.getName()))continue;
                try {
                    File fileTemp = getFileTemp(v);
                    v.transferTo(fileTemp);
                    Method method = param.getClass().getMethod("set"+StrUtil.upperFirst(k), String.class);
                    method.invoke(upload(fileTemp).key);
                } catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                //TODO 缓存文件是否删除
            }
        }
//        return returns;
    }

    @Override
    public DefaultPutRet uploadImage(String filePath,MultipartFile multipartFile) {
        return kodoService.uploadImage(filePath,multipartFile);
    }

    @Override
    public DefaultPutRet uploadImageByBytes(String filePath, byte[] uploadBytes) {
        return kodoService.uploadImageByBytes(filePath,uploadBytes);
    }

    @Override
    public DefaultPutRet uploadImageByFile(String filePath, File file) {
        return kodoService.uploadImageByFile(filePath,file);
    }

    private File getFileTemp(MultipartFile multipartFile){
        String fileUrl="D:\\temp\\"+ StringUtil.generateShortUuid()+"\\"+multipartFile.getOriginalFilename();
        return new File(fileUrl);
    }

    private DefaultPutRet upload(File file){
        String key;// TODO key值是否需要自定义生成规则
       return kodoService.upload(null,file.getAbsolutePath());
    }

}
